// pages/coupons/coupons.js
import { getCouponList, getCoupon, getUserCouponList} from '../../api/url.js'
import { formatTime } from '../../utils/util.js'
const app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fromPage:'',//从哪个页面跳转
    coupons:[],//优惠券列表
    originCoupons:[],//请求下来的优惠券原数据
  },
  /**
   * @method
   * @desc 选择优惠券
   */
  selectCoupon(e){
    let that=this
    if(that.data.fromPage==='confirmOrder'){
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      let item = e.currentTarget.dataset.item
      let temItem=that.data.originCoupons.find(val=>{
        return val.fVouchersId === item.fId
      })
      prevPage.setData({
        selectedCoupon: temItem
      })
      prevPage.calFinalPriTxt()
      wx.navigateBack({

      })
    }
    
  },
  /**
   * @method
   * @desc 点击领取优惠券
   */
  getCoupon(e) {
    if (app.globalData.userInfo && app.globalData.wxUserInfo) {
      let id = e.currentTarget.dataset.id
      wx.showLoading({
        title: '领取中',
        mask: true
      })
      wx.request({
        url: getCoupon,
        data:{
          fVouchersId: id,
          loginName: app.globalData.userInfo.loginname,
          token: wx.getStorageSync('token'),
          fUserId: app.globalData.userInfo.id
        },
        success(res){
          wx.hideLoading()
          if (res.data.code === 0) {
            wx.showToast({
              title: '领取成功！',
            })
          } else {
            wx.showToast({
              title: res.data.msg || '领取异常',
              icon: 'none'
            })
          }
        },
        fail(){
          wx.showToast({
            title: '领取失败',
            icon:'none'
          })
        }
      })
    } else {
      wx.showToast({
        title: '请登录',
        icon: 'none'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that=this
    that.setData({
      fromPage:options.fromPage,
    })
    switch(that.data.fromPage){
      case 'goodsDetail':
        wx.request({
          url: getCouponList,
          data:{
            page:1,
            size:9999
          },
          success(res){
            if(res.data.code===0){
              let temList=res.data.response.cont.list
              temList = temList.filter(val => val)
              temList.forEach(val => {
                if (typeof val.fBegin == 'number'){
                  val.beginTime = formatTime(val.fBegin).split(' ')[0]
                  val.endTime = formatTime(val.fEnd).split(' ')[0]
                }else{
                  val.beginTime = val.fBegin.split(' ')[0]
                  val.endTime = val.fEnd.split(' ')[0]
                }
              })
              that.setData({
                coupons:temList
              })
            }else{
              wx.showToast({
                title: '获取优惠券异常',
                icon:'none'
              })
            }
          }
        })
        break
      case 'confirmOrder':
        that.setData({
          totalPrice: options.totalPri
        })
        wx.request({
          url: getUserCouponList,
          data: {
            page: 1,
            size: 9999,
            loginName: app.globalData.userInfo.loginname,
            token: wx.getStorageSync('token'),
            userId: app.globalData.userInfo.id,
            fUserId: app.globalData.userInfo.id
          },
          success(res) {
            if (res.data.code === 0) {
              that.setData({
                originCoupons: res.data.response.cont.list
              })
              let temList = res.data.response.cont.list.map(val => val.vouchers)
              temList = temList.filter(val => val)
              temList = temList.filter(val => val.fMinMoney <= Number(that.data.totalPrice))
              temList.forEach(val => {
                if (typeof val.fBegin == 'number') {
                  val.beginTime = formatTime(val.fBegin).split(' ')[0]
                  val.endTime = formatTime(val.fEnd).split(' ')[0]
                } else {
                  val.beginTime = val.fBegin.split(' ')[0]
                  val.endTime = val.fEnd.split(' ')[0]
                }
              })
              that.setData({
                coupons: temList
              })
            } else {
              wx.showToast({
                title: '获取优惠券异常',
                icon: 'none'
              })
            }
          }
        })
        break
      case 'user':
        wx.request({
          url: getUserCouponList,
          data: {
            page: 1,
            size: 9999,
            loginName: app.globalData.userInfo.loginname,
            token: wx.getStorageSync('token'),
            userId: app.globalData.userInfo.id,
            fUserId: app.globalData.userInfo.id
          },
          success(res) {
            if (res.data.code === 0) {
              console.log('打印优惠券')
              console.log(res)
              let temList = res.data.response.cont.list.map(val => val.vouchers)
              temList = temList.filter(val => val)
              temList.forEach(val => {
                if (typeof val.fBegin == 'number') {
                  val.beginTime = formatTime(val.fBegin).split(' ')[0]
                  val.endTime = formatTime(val.fEnd).split(' ')[0]
                } else {
                  val.beginTime = val.fBegin.split(' ')[0]
                  val.endTime = val.fEnd.split(' ')[0]
                }
              })
              that.setData({
                coupons: temList
              })
            } else {
              wx.showToast({
                title: '获取优惠券异常',
                icon: 'none'
              })
            }
          }
        })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that=this
    that.setData({
      coupons: [],//优惠券列表
    })
    switch (that.data.fromPage) {
      case 'goodsDetail':
        wx.request({
          url: getCouponList,
          data: {
            page: 1,
            size: 9999
          },
          success(res) {
            if (res.data.code === 0) {
              let temList = res.data.response.cont.list
              temList = temList.filter(val => val)
              temList.forEach(val => {
                if (typeof val.fBegin == 'number') {
                  val.beginTime = formatTime(val.fBegin).split(' ')[0]
                  val.endTime = formatTime(val.fEnd).split(' ')[0]
                } else {
                  val.beginTime = val.fBegin.split(' ')[0]
                  val.endTime = val.fEnd.split(' ')[0]
                }
              })
              that.setData({
                coupons: temList
              })
            } else {
              wx.showToast({
                title: '获取优惠券异常',
                icon: 'none'
              })
            }
          }
        })
        break
      case 'confirmOrder':
        wx.request({
          url: getUserCouponList,
          data: {
            page: 1,
            size: 9999,
            loginName: app.globalData.userInfo.loginname,
            token: wx.getStorageSync('token'),
            userId: app.globalData.userInfo.id,
            fUserId: app.globalData.userInfo.id
          },
          success(res) {
            if (res.data.code === 0) {
              let temList = res.data.response.cont.list.map(val => val.vouchers)
              temList = temList.filter(val => val)
              temList = temList.filter(val => val.fMinMoney <= Number(that.data.totalPrice))
              temList.forEach(val => {
                if (typeof val.fBegin == 'number') {
                  val.beginTime = formatTime(val.fBegin).split(' ')[0]
                  val.endTime = formatTime(val.fEnd).split(' ')[0]
                } else {
                  val.beginTime = val.fBegin.split(' ')[0]
                  val.endTime = val.fEnd.split(' ')[0]
                }
              })
              that.setData({
                coupons: temList
              })
            } else {
              wx.showToast({
                title: '获取优惠券异常',
                icon: 'none'
              })
            }
          }
        })
        break
      case 'user':
        wx.request({
          url: getUserCouponList,
          data: {
            page: 1,
            size: 9999,
            loginName: app.globalData.userInfo.loginname,
            token: wx.getStorageSync('token'),
            userId: app.globalData.userInfo.id,
            fUserId: app.globalData.userInfo.id
          },
          success(res) {
            if (res.data.code === 0) {
              let temList = res.data.response.cont.list.map(val => val.vouchers)
              temList = temList.filter(val => val)
              temList.forEach(val => {
                if (typeof val.fBegin == 'number') {
                  val.beginTime = formatTime(val.fBegin).split(' ')[0]
                  val.endTime = formatTime(val.fEnd).split(' ')[0]
                } else {
                  val.beginTime = val.fBegin.split(' ')[0]
                  val.endTime = val.fEnd.split(' ')[0]
                }
              })
              that.setData({
                coupons: temList
              })
            } else {
              wx.showToast({
                title: '获取优惠券异常',
                icon: 'none'
              })
            }
          }
        })
    }
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})